import { ExceptionHandler } from './../../handler/exception.handler';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Tools } from './../../common/tools/tools';
import { Component, OnInit } from '@angular/core';
import { Place, PlaceType } from 'src/app/models';
import { PlaceService } from '../../services/place.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzContextMenuService, NzDropdownMenuComponent } from 'ng-zorro-antd/dropdown';
import { PlaceUseAxisService } from 'src/app/common/place-use-axis/place-use-axis.service';
import * as dayjs from 'dayjs';
import { NzModalService } from 'ng-zorro-antd/modal';
// import * as Enumerable from 'linq';

@Component({
  selector: 'zepride-place',
  templateUrl: './place.component.html',
  styleUrls: ['./place.component.less']
})
export class PlaceComponent implements OnInit {
  orgId: string;
  placeTypeList: PlaceType[] = [];
  placeTypeModalVisible: boolean;
  placeTypeFormGroup: FormGroup;
  rightPlaceType: PlaceType;
  selectedPlaceType: PlaceType;

  placeModalVisible: boolean;
  placeFormGroup: FormGroup;
  placeList: Place[] = [];
  selectedPlace: Place;
  initDate: Date[];


  constructor(
    public psvr: PlaceService,
    public fb: FormBuilder,
    private nzContextMenuService: NzContextMenuService,
    private msg: NzMessageService,
    private axisSvr: PlaceUseAxisService,
    private modal: NzModalService
  ) {
    this.orgId = localStorage.getItem('orgid');
  }

  async ngOnInit() {
    await this.queryPlaceType();
    if (this.placeTypeList.length > 0) {
      this.placeTypeClick(this.placeTypeList[0]);
    }

    this.placeTypeFormGroup = this.fb.group({
      placeTypeName: ['', [Validators.required, Validators.maxLength(10)]],
    });

    this.placeFormGroup = this.fb.group({
      placeTypeId: [this.selectedPlaceType.id, [Validators.required]],
      name: ['', [Validators.required, Validators.maxLength(20)]],
      count: [1, [Validators.required, Validators.max(1000)]],
      note: ['', [Validators.maxLength(100)]]
    });
  }

  async queryPlaceType() {
    this.placeTypeList = await this.psvr.queryPlaceType({ orgId: this.orgId });
  }

  addPlaceType() {
    this.placeTypeModalVisible = true;
    this.selectedPlaceType = null;
  }

  placeTypeModalCancel() {
    this.placeTypeModalVisible = false;
    this.placeTypeFormGroup.reset();
  }

  async placeTypeModalOk() {
    if (this.placeTypeValidate()) {

      if (this.selectedPlaceType) {
        this.selectedPlaceType.name = this.placeTypeFormGroup.controls.placeTypeName.value;
        await this.psvr.updatePlaceType(this.selectedPlaceType);
      }
      else {
        let placeType = new PlaceType();
        placeType.id = Tools.GetGuid();
        placeType.name = this.placeTypeFormGroup.controls.placeTypeName.value;
        placeType.orgId = this.orgId;
        await this.psvr.createPlaceType(placeType);
        this.selectedPlaceType = placeType;
      }

      this.placeTypeModalVisible = false;

      this.placeTypeFormGroup.reset();

      await this.queryPlaceType();
    }
  }

  placeTypeValidate() {
    for (const ctrl in this.placeTypeFormGroup.controls) {
      if (Object.prototype.hasOwnProperty.call(this.placeTypeFormGroup.controls, ctrl)) {
        const control = this.placeTypeFormGroup.controls[ctrl];
        control.markAsTouched();
        control.updateValueAndValidity();
      }
    }
    return this.placeTypeFormGroup.valid;
  }

  async placeTypeClick(item: PlaceType) {
    this.placeTypeList.forEach(x => x.selected = false);
    item.selected = true;
    this.selectedPlaceType = item;

    await this.queryPlace();
  }

  contextMenu($event: MouseEvent, menu: NzDropdownMenuComponent, placeType: PlaceType) {
    this.rightPlaceType = placeType;
    this.nzContextMenuService.create($event, menu);
  }

  editPlaceType() {
    this.placeTypeModalVisible = true;
    this.selectedPlaceType = this.rightPlaceType;
    this.placeTypeFormGroup.controls.placeTypeName.setValue(this.selectedPlaceType.name);
  }
  async delPlaceType() {
    this.modal.confirm({
      nzTitle: `提示信息`,
      nzContent: `是否要删除【${this.rightPlaceType.name}】？`,
      nzOkText: '删除',
      nzOkType: 'primary',
      nzOnOk: async () => {
        try {
          await this.psvr.delPlaceType(this.rightPlaceType.id);
          this.msg.success('操作成功！');
          await this.queryPlaceType();
        } catch (error) {
          ExceptionHandler.current.handleError(error);
        }
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });

  }

  addPlace() {
    this.placeModalVisible = true;
  }

  placeModalCancel() {
    this.placeModalVisible = false;
    this.placeFormGroup.reset();
  }

  placeValidate() {
    for (const ctrl in this.placeFormGroup.controls) {
      if (Object.prototype.hasOwnProperty.call(this.placeFormGroup.controls, ctrl)) {
        const control = this.placeFormGroup.controls[ctrl];
        control.markAsTouched();
        control.updateValueAndValidity();
      }
    }
    return this.placeFormGroup.valid;
  }

  async placeModalOk() {
    try {
      if (this.placeValidate()) {

        if (this.selectedPlace) {
          let place = this.selectedPlace;
          place.name = this.placeFormGroup.controls.name.value;
          place.count = this.placeFormGroup.controls.count.value;
          place.note = this.placeFormGroup.controls.note.value;
          place.placeTypeId = this.placeFormGroup.controls.placeTypeId.value;
          place.orgId = this.orgId;

          await this.psvr.updatePlace(place);
        }
        else {
          let place = new Place();
          place.id = Tools.GetGuid();
          place.name = this.placeFormGroup.controls.name.value;
          place.count = this.placeFormGroup.controls.count.value;
          place.note = this.placeFormGroup.controls.note.value;
          place.placeTypeId = this.placeFormGroup.controls.placeTypeId.value;
          place.orgId = this.orgId;

          await this.psvr.createPlace(place);
        }
        this.selectedPlace = null;

        this.placeModalVisible = false;

        this.placeFormGroup.reset();

        await this.placeTypeClick(this.selectedPlaceType);
      }
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }

  }

  async queryPlace(params: any = {}) {
    try {
      this.placeList = await this.psvr.queryPlace({
        orgId: this.orgId,
        placeTypeId: this.selectedPlaceType.id,
        ...params
      });

      this.placeList.forEach(x => {
        x.color = Tools.getRandColor()
      });
    } catch (error) {
      ExceptionHandler.current.handleError(error);
    }
  }

  async dateChange(value: Date[]) {
    if (value.length == 0) {
      //表示清空查询时间的条件
      await this.queryPlace();
    }
    else {
      if (value[0].getTime() < Date.now()) {
        value[0] = new Date();
      }

      this.placeList = this.placeList.filter(item => {
        if (item.placeUseLogs.length == 0) {
          return true;
        }
        else {
          const rList = item.placeUseLogs.filter(log => log.endTime >= value[0].getTime() && log.endTime < value[1].getTime());
          return rList.length == 0;
        }
      });
    }

  }

  async placeExpand(item: Place) {
    item.expand = !item.expand;
    const placeInfo = await this.psvr.getPlaceById(item.id);
    // item.placeUseLogs = placeInfo.placeUseLogs;
    let begin: number;
    let end: number;

    if (this.initDate) {
      begin = this.initDate[0].getTime();
      if (begin < Date.now()) {
        begin = Date.now();
      }
      end = this.initDate[1].getTime();
    }
    else {
      begin = Date.now();
      end = dayjs(begin).add(1, 'day').valueOf();
    }
    const fragmentList = this.axisSvr.sliceTheTime(placeInfo.placeUseLogs, begin, end);
    this.axisSvr.setDataValue$.next({
      fragmentList,
      begin,
      end
    });
  }

  editPlace(item: Place) {
    this.placeModalVisible = true;

    this.placeFormGroup.controls.placeTypeId.setValue(item.placeTypeId);
    this.placeFormGroup.controls.name.setValue(item.name);
    this.placeFormGroup.controls.count.setValue(item.count);
    this.placeFormGroup.controls.note.setValue(item.note);

    this.selectedPlace = item;
  }

  delPlace(item: Place) {
    this.modal.confirm({
      nzTitle: `提示信息`,
      nzContent: `是否要删除【${item.name}】？`,
      nzOkText: '删除',
      nzOkType: 'primary',
      nzOnOk: async () => {
        try {
          await this.psvr.deletePlace(item.id);
          await this.queryPlace();
          this.msg.success('删除成功！');
        } catch (error) {
          ExceptionHandler.current.handleError(error);
        }
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });

  }
}
